var express = require('express');
var router = express.Router();
var crypto = require('crypto');


var mongoose = require('mongoose');
// 用户模型
var user=require('../models/user');
//留言板模型
// var message=require('../models/message.js');



/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', {
    title: '主页',
    user: req.session.user,
    success: req.flash('success').toString(),
    error: req.flash('error').toString()
   });
});
router.get('/register', function(req, res, next) {
  res.render('register', {
    title: '注册',
    user: req.session.user,
    success: req.flash('success').toString(),
    error: req.flash('error').toString()
  });
});
router.get('/login',checkNotLogin,function (req, res) {
    res.render('login', {
        title: '登录',
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
    });
});

router.post('/register',async function (req, res) {
  var name = req.body.name,
      password = req.body.password,
      password_re = req.body['password-repeat'];
  //检验用户两次输入的密码是否一致
  if (password_re != password) {
    req.flash('error', '两次输入的密码不一致!');
    return res.redirect('/index/register');//返回注册页
  }
  //生成密码的 md5 值
  var md5 = crypto.createHash('md5'),
      password = md5.update(req.body.password).digest('hex');
  //用户模型创建出Entity
  var userEntity=new user({
    name: name,
    password: password,
    email: req.body.email
  });
  var userCount=await user.count({"name":name})
  // console.log(userCount,"存在用户的数量");
  if(userCount!=0){
    // res.json({
    //   status:500,
    //   msg:"用户已经存在"
    // })
    // return next();
    req.flash('error', '用户已存在!');
    return res.redirect('/index/register');//返回注册页
  }else{
    var isSave=await userEntity.save();
    if(!isSave){
      // res.json({
      //   status:500,
      //   msg:"注册失败"
      // })
      req.flash('error', err);
      return res.redirect('/index/register');//注册失败返回主册页
    }else{
      // res.json({
      //   status:200,
      //   msg:"注册成功"
      // })
      req.session.user = userEntity;//用户信息存入 session
      // console.log(req.session.user,userEntity);
      req.flash('success', '注册成功!');
      res.redirect('/');//注册成功后返回主页
    }
  }
});

router.post('/login',async function (req, res) {
  //生成密码的 md5 值
  var md5 = crypto.createHash('md5'),
      password = md5.update(req.body.password).digest('hex');
  var doc=await user.find({name:req.body.name});
  if(doc==""){
    req.flash('error', '用户不存在!');
    return res.redirect('/index/login');//用户不存在则跳转到登录页
  }else{
    if(password!=doc[0].password){
      req.flash('error', '密码错误!');
      return res.redirect('/index/login');//密码错误则跳转到登录页
    }else{
      //用户名密码都匹配后，将用户信息存入 session
      req.session.user = doc[0];
      req.flash('success', '登陆成功!');
      res.redirect('/');//登陆成功后跳转到主页
    }
  }
});

router.get('/logout', checkLogin,function (req, res) {
  req.session.user = null;
  req.flash('success', '登出成功!');
  res.redirect('/');//登出成功后跳转到主页
});




function checkLogin(req, res, next) {
  if (!req.session.user) {
    req.flash('error', '未登录!');
    res.redirect('/index/login');
  }
  next();
}

function checkNotLogin(req, res, next) {
  console.log(req.session.user,"是否已登录");
  if (req.session.user) {
    req.flash('error', '已登录!');
    res.redirect('/');
  }
  next();
}

module.exports = router;




